from flask import jsonify

from app.globals import env
from app.mod_base.restless import create_blueprint
from app.mod_trade.model.mongo import Account
from app.mod_trade.schema import marsh_schema, args_schema


def account_changed(method, model, data, id_):
    if method == 'PUT':
        worker = env.workers.get(data['account'])
        if worker:
            for k, v in data.items():
                setattr(worker.account, k, v)


bp_account = create_blueprint(
    Account,
    'accounts',
    args_schema.AccountSchema,
    marsh_schema.AccountSchema,
    methods=['POST', 'GET', 'PUT', 'DELETE'],
    callback=account_changed
)


@bp_account.route('/account/stats')
def stats():
    accounts = [e.account for e in env.workers.values()]
    return jsonify(marsh_schema.AccountSchema(many=True).dump(accounts))
